package com.wp.controller;
import com.wp.entity.SysUser;
import com.wp.service.SysUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class Login{

    @Resource
    private SysUserService service;

    // 捕获异常信息
    @ExceptionHandler(value = {RuntimeException.class})
    public String handException(RuntimeException exception,HttpServletRequest req){
        req.setAttribute("e",exception);
        return "login";
    }

    // 条登录页面
    @RequestMapping("/toLogin")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String doLogin(HttpServletRequest request, HttpSession session, String account, String password) {

        SysUser sysUser = service.login(account,password);

        if (null !=sysUser) {
            // 将登录的用户放入session中
            request.getSession().setAttribute("UserSession",sysUser);

            return "redirect:/user/toMain";
        }else{
            // 异常处理
            throw  new RuntimeException("用户名或密码错误");
        }
    }

    // 跳转到首页
    @RequestMapping("/toMain")
    public String main() {
        return "frame";
    }

    // 退出页面
    @RequestMapping("/logout")

    public String logout(HttpServletRequest request){

        request.getSession().removeAttribute("UserSession");

        return "login";
    }
}
